package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer1 {
    ServerSocket socket = null;
    public TcpEchoServer1(int port) throws IOException {
        socket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
//        ExecutorService pool = Executors.newCachedThreadPool();
        while(true){
            Socket clientSocket = socket.accept();
//            pool.submit(new Runnable() {
//                @Override
//                public void run() {
//                    processConnection(clientSocket);
//                }
//            });
            Thread t = new Thread(() ->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s : %d] 服务器上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream();
            PrintWriter writer = new PrintWriter(outputStream)) {
            Scanner sc = new Scanner(inputStream);
            while(true){
                if(!sc.hasNext()){
                    System.out.printf("[%s : %d] 服务器下线\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                String request = sc.next();
                String response = process(request);
                writer.println(response);
                writer.flush();
                System.out.printf("[%s : %d] req : %s resp : %s\n",clientSocket.getInetAddress(),clientSocket.getPort()
                , request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer1 server1 = new TcpEchoServer1(9090);
        server1.start();
    }
}
